//
//  LXJNetworkManager.swift
//  XJWeiBo
//
//  Created by 李旭杰 on 2017/3/27.
//  Copyright © 2017年 李旭杰. All rights reserved.
//

import UIKit
import AFNetworking

/// 网络请求的工具类

/// 网络请求类型
enum RequestType: Int {
    /// get 方式请求
    case get = 0
    /// post方式请求
    case post = 1
}

class LXJNetworkManager: AFHTTPSessionManager {
    // MARK: AppKey AppSecre 属性 和 redirect_uri 属性
    let AppKey = "2606577968"
    let AppSecret = "250ceb5c4fd959918eb96b676aef99ce"
    let redirect_uri = "https://user.qzone.qq.com"
    
    // MARK: 单例,全局访问点
    static var sharedManager: LXJNetworkManager = {
        let manager = LXJNetworkManager()
        /// 追加 afn 支持的数据类型
        manager.responseSerializer.acceptableContentTypes?.insert("text/html")
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return manager
    }()
    
    // MARK: 网络请求
    fileprivate func requestNetworkingData(requestType: RequestType,URLString: String, parameters: Any?, completion: ((Any?, Error?) -> ())?) -> Void {
        if requestType == .get {
            get(URLString, parameters: parameters, progress: nil, success: { (dataTask, response) in
                /// 执行闭包
                completion!(response, nil)
            }, failure: { (dataTask, error) in
                /// 执行闭包
                completion!(nil, error)
            })
        } else{
            post(URLString, parameters: parameters, progress: nil, success: { (dataTask, response) in
                /// 执行闭包
                completion!(response, nil)
            }, failure: { (dataTask, error) in
                /// 执行闭包
                completion!(nil, error)
            })
        }
    }
    
}
// MARK: 获取粉丝信息
extension LXJNetworkManager{
    /// 获取粉丝列表数据
    func requestWeiboFansInfo(access_token: String, userID: Int64, completion:@escaping ((Any?, Error?) -> ())) -> Void {
        /// 请求地址
        let urlStr = "https://api.weibo.com/2/friendships/followers.json"
        
        /// 网络请求参数
        let parameters = [
            "access_token":access_token,
            "uid":userID,
            "count":50
            ] as [String : Any]
        
        /// 发起网络请求
        requestNetworkingData(requestType: .get, URLString: urlStr, parameters: parameters, completion: completion)
    }
}

// MARK: 发微博
extension LXJNetworkManager {
    /// 发送文字带一张图片的微博
    func sendWeiboMessage(access_token: String, status: String, image: UIImage, completion:@escaping ((Any?, Error?) -> ())) -> Void {
        /// 请求地址
        let urlStr = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        /// 网络请求参数
        let parameters = [
            "access_token":access_token,
            "status":status
            ] as [String : Any]
        
        /// 发起请求
        post(urlStr, parameters: parameters, constructingBodyWith: { (formData) in
            /// 获取图片的二进制数据
            let imageData = UIImageJPEGRepresentation(image, 1)
            /// 上传图片
            formData.appendPart(withFileData: imageData!, name: "pic", fileName: "hehe", mimeType: "JPEG/GIF/PNG")
        }, progress: nil, success: { (_, response) in
            completion(response, nil)
        }) { (_, error) in
            completion(nil, error)
        }
    }
    
    /// 发送文字微博
    func sendWeiboMessage(access_token: String, status: String, completion:@escaping ((Any?, Error?) -> ())) -> Void {
        /// 请求地址
        let urlStr = "https://api.weibo.com/2/statuses/update.json"
        
        /// 网络请求参数
        let parameters = [
            "access_token":access_token,
            "status":status
            ] as [String : Any]
        
        /// 发起请求
        requestNetworkingData(requestType: .post, URLString: urlStr, parameters: parameters, completion: completion)
    }
}

// MARK: 发起微博首页的网络请求
extension LXJNetworkManager {
    // MARK: 获取当前登录用户及其所关注（授权）用户的最新微博
    func requestHomeWeiboInfo(access_token: String, uid: Int64,completion:@escaping ((Any?, Error?) -> ())) -> Void {
        /// 获取首页的资源地址
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        let url = urlStr + "?access_token=\(access_token)"
        print("获取当前登录用户及其所关注（授权）用户的最新微博:\(url)")
        
        /// 网络请求参数
        let parameters = [
            "access_token":access_token,
            ] as [String : Any]
        
        /// 发起网络请求
        requestNetworkingData(requestType: .get, URLString: urlStr, parameters: parameters, completion: completion)
    }
}

// MARK: 发起授权登录的网络请求
extension LXJNetworkManager {
    // MARK: 根据用户ID获取用户信息
    
    /// 获取用户信息
    ///
    /// - Parameters:
    ///   - access_token: 令牌 token
    ///   - uid:  用户 id
    ///   - completion:  请求完成之后的数据回调
    func requestDataForUserInfo(access_token: String, uid: Int64, completion:@escaping ((Any?, Error?) -> ())) -> Void {
        /// 获取令牌的资源路径
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        /// 网络请求参数
        let parameters = [
            "access_token":access_token,
            "uid":uid
            ] as [String : Any]
        
        /// 发起网络请求
        requestNetworkingData(requestType: .get, URLString: urlStr, parameters: parameters, completion: completion)
    }
    
    // MARK: 获取授权过的Access Token
    
    /// f发起获取授权过的AccessToken的网络请求
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 请求完成之后的数据回调
    func requestDataForAccessToken(code: String, completion:@escaping ((Any?, Error?) -> ())) -> Void {
        /// 获取令牌的资源路径
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        /// 网络请求参数
        let parameters = [
            "client_id":AppKey,
            "client_secret":AppSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        
        /// 发起网络请求
        requestNetworkingData(requestType: .post, URLString: urlStr, parameters: parameters, completion: completion)
    }
}
